package com.example.test001;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;

import java.util.concurrent.ThreadFactory;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.atomic.AtomicInteger;

@Configuration
public class AppConfig {

    // 定义一个自定义的ThreadFactory
//    class CustomThreadFactory implements ThreadFactory {
//        private final AtomicInteger threadNumber = new AtomicInteger(1);
//        private final ThreadGroup group;
//        private final String namePrefix;
//
//        // 构造函数，传入线程前缀
//        public CustomThreadFactory(String namePrefix) {
//            SecurityManager s = System.getSecurityManager();
//            group = (s != null) ? s.getThreadGroup() : Thread.currentThread().getThreadGroup();
//            this.namePrefix = namePrefix;
//            System.out.println("CustomThreadFactory: group" + this.namePrefix);
//        }
//
//        @Override
//        public Thread newThread(Runnable r) {
//            Thread t = new Thread(group, r, namePrefix + threadNumber.getAndIncrement(), 0);
//            // 如果线程是守护线程，将其设置为非守护线程，以便它能阻止JVM退出
//            if (t.isDaemon())
//                t.setDaemon(false);
//            // 如果线程优先级不正常，将其设置为默认优先级
//            if (t.getPriority() != Thread.NORM_PRIORITY)
//                t.setPriority(Thread.NORM_PRIORITY);
//            return t;
//        }
//    }
//
//    // 配置线程池bean
//    @Bean("stockTaskExecutor1")
//    public ThreadPoolTaskExecutor stockTaskExecutor1() {
//        ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();
//        executor.setCorePoolSize(5); // 核心线程数
//        executor.setMaxPoolSize(10); // 最大线程数
//        executor.setQueueCapacity(25); // 队列容量
//        executor.setKeepAliveSeconds(60); // 非核心线程存活时间
//        executor.setThreadNamePrefix("stockTaskExecutor-"); // 前缀
//
//        // 使用自定义的ThreadFactory
//        executor.setThreadFactory(new CustomThreadFactory(executor.getThreadNamePrefix()));
//
//        // 拒绝策略：调用者运行
//        executor.setRejectedExecutionHandler(new ThreadPoolExecutor.CallerRunsPolicy());
//
//        // 初始化线程池
//        executor.initialize();
//        return executor;
//    }
}
